from flask_sqlalchemy import SQLAlchemy
from packages.core.db.decorators import Transactional
from packages.core.auth.login_user_holder import LoginUserHolder
from modules.sys.models.dict_item import DictItem
from packages.tools.base_tool import generate_id
from packages.tools.db_tool import DbTool
from modules.sys.validators.dict_item_validator import DictItemForm, DictItemPageForm
from packages.common.base import IdForm, IdsForm


class DictItemService():
    """
    字典项模块业务处理类
    """
    def __init__(self, db: SQLAlchemy):
        self.model = DictItem
        self.db = db

    def detail(self, form: IdForm):
        """
        通过id获取信息
        :param form:
        :return:
        """
        model = self.db.session.query(self.model).get(form.id.data)
        return model

    def page(self, form: DictItemPageForm):
        """
        分页查询列表
        :param form:
        :return:
        """
        # 可通过form.data获取所有提交参数
        # 可通过form.pageNum.data获取pageNum
        # 可通过form.pageSize.data获取pageSize
        # page=self.db.query(User).filter().paginate(form.pageNum.data, form.pageSize.data,False)
        pageNum = form.data.get("pageNum", 1)
        pageSize = form.data.get("pageSize", 10)
        page = DbTool.filter_by_custom(self.model).paginate(page=pageNum, per_page=pageSize, error_out=False)
        return self.model.to_page(page)

    @Transactional()
    def save(self, form: DictItemForm):
        """
        添加字典项
        :param form:
        :return:
        """
        model = self.model(**form.data)
        q = self.db.session.query(DictItem)
        q = q.filter_by(dictId=model.dictId)
        DbTool.check_unique(DictItem, "code", model.code, None, "唯一编码已存在！", q)
        model.id = generate_id()
        model.createUser = LoginUserHolder.get_user_id()
        model.updateUser = LoginUserHolder.get_user_id()
        self.db.session.add(model)

    @Transactional()
    def update(self, form: DictItemForm):
        """
        修改字典项
        :param form:
        :return:
        """
        model = self.model(**form.data)
        q = self.db.session.query(DictItem)
        q.filter_by(dictId=model.dictId)
        DbTool.check_unique(DictItem, "code", model.code, model.id, "唯一编码已存在！", q)
        model.updateUser = LoginUserHolder.get_user_id()

        self.db.session.query(self.model).filter_by(id=form.id.data).update(
            model.to_dict()
        )

    @Transactional()
    def remove(self, form: IdsForm):
        """
        删除
        :param form:
        :return:
        """
        self.model().remove(self.model, form.ids.data)
